<template>

  <div>
    <el-button type="primary" @click="grant" size="mini">授权</el-button>

    <el-tree
        ref="tree"
        style="max-height: 400px;overflow-y: auto"
        :data="data"
        show-checkbox
        node-key="menuId"
        :props="defaultProps">
    </el-tree>

  </div>


</template>

<script>

import request from '@/utils/request'

export default {

  name: 'RoleMenu',
  props:[
    'roleId'
  ],
  data() {
    return {
      data: [],
      defaultProps: {
        label: 'menuName',
        children: 'children'
      }

    }
  },
  methods: {
    loadTree(){
      request({
        method: 'get',
        url: '/sysMenu/loadTree',
      }).then(list => {

        this.data = list;

        this.loadMenuIdsByRole();
      })

    },

    //根据角色查询已经授权的 菜单ID
    loadMenuIdsByRole(){
      request({
        method: 'get',
        url: '/sysRole/loadMenuIdsByRole/'+this.roleId,
      }).then(menuIdArray => {

         console.log("menuIdArray", menuIdArray)
        menuIdArray.forEach((menuId)=>{
          this.$refs['tree'].setChecked(menuId,true,false);
        })

      })
    },
    //给角色授权菜单
    grant(){

      let checkedNodes = this.$refs['tree'].getCheckedNodes(false,true);

      console.log("checkedNodes",checkedNodes);

      let menuIds = [];// 所有选中的菜单 ID
      checkedNodes.forEach((item)=>{
        menuIds.push(item.menuId)
      })
      // console.log("menuIds",menuIds);
      // console.log("roleId",this.roleId);


      request({
        method: 'post',
        url: '/sysRole/grant',
        data:{
          roleId:this.roleId,
          menuIds:menuIds
        }
      }).then(succes => {
        if(succes){
          this.$message({
            type:'success',
            message:'授权成功'
          })
          //关闭当前的gialog
          this.$emit("update:dialogVisible2",false)
        }
      })




    }
  },
  created() {

    //组件初始化的时候查询

    this.loadTree();


  }


}


</script>

<style>
.title {
  height: 40px;
  line-height: 40px;
}
</style>